<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>部门管理</title>
    <link rel="stylesheet" href="/css/element.css" />
  </head>
  <body>
    <script src="/js/Vue.js"></script>
    <script src="/js/element.js"></script>
    <script src="/js/axios.js"></script>
    <script src="/js/Qs.js"></script>
    <script type="text/javascript" src="/js/layer.js"></script>
    <style>
      #app {
        height: 100%;
      }
      #search .el-card__body {
        height: 45px;
      }
      #tools .el-card__body {
        padding: 5px 5px 5px 20px;
      }
      #table {
        height: calc(100% - 144px);
      }
      .layui-layout-admin .layui-body .layadmin-tabsbody-item {
        padding: 5px;
      }

      #tools .el-button {
        padding: 10px 8px 10px 5px;
        background-color:whitesmoke !important;
        color: black !important;
        border: none !important;
      }
      /* .el-button {
        margin-left: 0 !important;
      } */
      .el-input__inner {
        height: 38px;
      }

      .text {
        font-size: 14px;
      }

      .item {
        padding: 18px 0;
      }

      .el-card {
        width: 100%;
        box-sizing: border-box;
        margin-bottom: 2px;
      }

      .el-table_1_column_5:hover {
        cursor: pointer;
        border-bottom: 2px solid #409eff;
      }
      /*翻页样式*/
      .el-pagination {
        margin-top: 5px;
      }
      .el-form-item label{
        text-align: left !important;
        width: 68px !important;
        vertical-align: middle;
        float: left;
        font-size: 14px;
        color: #606266;
        line-height: 40px;
        padding: 0 12px 0 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
      }
      .el-form-item__content {
      line-height: 40px;
      font-size: 14px;
      }
      .el-button--medium{
        padding: 10px 20px;
        font-size: 14px;
        border-radius: 4px;
      }
    </style>
    <div id="app">
      <!--    查询框-->
      <el-card id="search">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="搜索 ">
            <el-input clearable placeholder="请输入要查询的内容" style="width:200px;" v-model="searchForm.keyword"></el-input>
          </el-form-item>
          <el-form-item label="所属单位">
            <el-select v-model="unit">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                ></el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              size="medium"
              type="primary"
              @click="asSearchHandle"
              size="large"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
      <!--工具栏-->
      <el-card id="tools">
        <el-row>
          <el-button
            size="normal"
            icon="el-icon-document-add"
            type="primary"
            @click="addDeptAction"
          >
            创建部门
          </el-button>
          <el-button
          size="normal"
          icon="el-icon-delete"
          type="primary"
          @click="changSelectUserState"
        >
          删除部门
        </el-button>
        <el-popconfirm></el-popconfirm>
          <el-button
            size="normal"
            icon="el-icon-document-add"
            type="primary"
            @click="disAssumptionAction"
          >
            批量导入
          </el-button>
        </el-row>
      </el-card>
      <!--    查询数据展示表格-->
      <el-card id="table">
        <el-table
          border
          :stripe="true"
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :select-on-indeterminate="false"
          :key="updatakey"
        >
          <el-table-column prop="id" label="部门ID" align="center"> </el-table-column>
          <el-table-column prop="name" label="部门名称" align="center"> </el-table-column>
          <el-table-column label="所属单位id" prop="companyid" align="center"> </el-table-column>
          <el-table-column label="所属部门id" prop="parent" align="center"> </el-table-column>
          <el-table-column label="操作" align="center" width="320">
            <template slot-scope="scope">
                <!-- "isTemplate"为true 则显示 编辑模板按钮-->
                <el-link v-if="scope.row.isTemplate" icon="el-icon-edit-outline" @click="sceneNameEditAction(scope.$index, scope.row)" type="success">修改场景名称</el-link>
                <el-link icon="el-icon-edit-outline" @click="editDeptAction(scope.$index,scope.row)" type="primary">修改</el-link>
                <el-popconfirm title=" 确定要删除该部门？(子部门会一并删除)" @confirm="deleteDept(scope.$index, scope.row)">
                    <el-link slot="reference" icon="el-icon-delete" type="danger">删除</el-link>
                </el-popconfirm>
            </template>
        </el-table-column>
        </el-table>
        <!--        页码-->
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total,prev, pager, next, jumper"
          :total="totaldata"
        >
        </el-pagination>
      </el-card>
    </div>
    <script src="/js/formDataUtils.js"></script>
    <script>
      var companyid;
      var categoryList = [];
      var datetree = [];
      var addwindow = null;
      var editwindow = null;
      var that;
      var asid;
      var addept_name = '';//增加的部门的名称
      var addeptname ='';//增加部门的父节点名称
      var addeptid = '';//增加部门的父节点ID
      var vue = new Vue({
        el: "#app",
        data(){
          return {
          addusername:'',
          addnickname:'',
          editedptname:'',
          unit:'',//这个值不设置控件显示不会更新
          updatakey:false,    
          //翻页相关数据
          totaldata:4,
          currentPage: 1,
          pageSize: 10,
          
          //查询数据
          searchForm: {
            categoryid: "",
            keyword: "",
          },
          file: "",
          //文件列表
          fileList: [],
          //预案类型
          categoryList: [{categoryName:'全部',categoryid:0}],
          //表格数据选中seltion数据
          multipleSelection: [],
          }
        },

        filters:{

		},
    mounted() {
            const that = this;
 
            //获取所有单位类型
            this.getCompany();
            //查询表格数据
            this.asSearch();
        },

        // filters: {
        //   asType(val) {
        //     const typeArray = that.categoryList;
        //     for (let i = 0; i < typeArray.length; i++) {
        //       if (typeArray[i].categoryId == val) {
        //         return typeArray[i].categoryName;
        //       }
        //     }
        //   },
        // },
        // beforeCreate() {
        //   that = this;
        // },
        // mounted() {
        //   //获取所有预案类别
        //   this.getCategory();
        //   //默认进入页面时查询预案
        //   this.asSearch();
        // },
     watch:
     {
        
     }   ,
        methods: {
          //删除预案
          deleteAssumption() {
            const that = this;
            const LIST = this.multipleSelection;
            if (LIST.length >= 1) {
              layer.confirm(
                "确定要删除吗？",
                { icon: 3, title: "警告" },
                function (index) {
                  let result_arr = [];
                  for (let i = 0; i < LIST.length; i++) {
                    result_arr.push(LIST[i].asid);
                  }
                  let id = result_arr.join(",");
                  //发送删除预案请求
                  let params = new FormData();
                  params.append("id", id);
                  axios
                    .post("/assumption/delete", params)
                    .then((res) => {
                      if (res.data.success) {
                        that.$message.success("删除成功！");
                        //纠正页页码
                        that.deleteCorrect(that.tableData, result_arr.length);
                        //刷新页面
                        that.asSearch();
                      } else {
                        that.$message.error(res.data.message);
                      }
                    })
                    .catch((err) => {
                      console.log(err);
                    });
                  //关闭提醒框
                  layer.close(index);
                }
              );
            } else {
              layer.alert("请勾选预案后再点击删除！");
            }
          },
          //最后一页最后一条数据删除时，页码纠正
          deleteCorrect(data, namuber) {
            const totalPage = Math.ceil(
              (data.length - namuber) / this.pageSize
            ); // 总页数
            this.currentPage =
              this.currentPage > totalPage ? totalPage : this.currentPage;
            this.currentPage = this.currentPage < 1 ? 1 : this.currentPage;
          },
          //新建部门弹出窗口
          addDeptAction() {
            const that = this;
            //打开弹窗
            addwindow = layer.open({
            type: 2,
            title: "新建部门",
            shadeClose: true,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ["533px", "500px"],
            content: "/dialog/system/adddept.html",
            cancel: function () {
                      addeptid='';
                      addeptname='';
                      console.log('cancel...')
            },
                  end: () => {
                 
                      if(addeptname&&addept_name)
                      {
                        console.log('增加部门所属:'+addeptname+' 增加部门名称:'+addept_name+' 父节点id:'+addeptid + '单位id:'+companyid);
                        this.addNewDept(addept_name,addeptid);
                      }
                      else 
                      {
                          console.log('end...')
                      }
                      //this.searchAllScene();
                      //sceneData = {};
                  }
            });
          },

          //新建部门
          addNewDept(name,did) {
              let params = {
                  companyid:companyid,
                  name:name,
                  parent:did,
              }
              var that = this;
          $.post('syatem/add_dept', params, function (data) {
                  console.log(data);
                  if(data.success)
                  {
                      console.log('sucess~');
                      that.asSearch();
                      that.updatakey=!this.updatakey;
                  }
                  else 
                  {
                      console.log('error!!!'+data.message);
                      //alert(data.message);
                  }
                  //console.log(data.data.content);
                  //刷新表格
              })
            }, 

          //弹出编辑部门窗口
          editDeptAction(index, row) {
          //场景id赋值
          //console.log(index);
          console.log(row);
          sceneId = row.id;
          //数据回显赋值
          sceneData = row;
          //打开弹窗
          editwindow=layer.open({
              type: 2,
              title: '修改',
              shadeClose: true,
              shade: false,
              maxmin: true, //开启最大化最小化按钮
              area: ['400px', '400px'],
              content: '/dialog/system/editdept.html',
              cancel: function () {
                  editedptname='';
                  console.log('cancel...')
        },
              end: () => {
                  if(editedptname)
                  {
                      console.log('更新部门ID:'+sceneId);
                      //this.editDept(sceneId,editedptname);
                      //this.addNewCompany(addname);
                  }
                  else 
                  {
                      console.log('end...')
                  }
                  //this.searchAllScene();
                  //sceneData = {};
              }
          });
      },

        //编辑部门(暂无接口支持)
        editDept(deptid,dname) {
            let params = {
                id:deptid,
                name:dname,
            }
            var that = this;
        $.post('syatem/update_Dept', params, function (data) {
                //console.log(data);
                if(data.success)
                {
                    console.log('sucess~');
                    that.searchAllScene();
                    that.updatakey=!this.updatakey;
                }
                else 
                {
                    console.log('error!!!'+data.message);
                }
                //console.log(data.data.content);
                //刷新表格
            })
          },

          //删除部门 (暂无接口支持)
          deleteDept(index, row) {
                console.log('del'+'id:'+row.id);
                // let url = action==1?'/syatem/recover_User':'/syatem/forbidden_User';
                // let pid_data = row.id;
                // //result_arr[0]=row.id;
                // //result_arr[1] = 3;
                // var that = this;
                // let pid_arr_data = pid_arr.join(',');
                // console.log('pid_arr:'+pid_arr+'\n'+'pid_data:'+pid_data+'pid_arr_data:'+pid_arr_data);
                //   let params  = 
                //    {
                //       pid:pid_data
                //    }
                // $.post(url, params, function (data) {
                //     //console.log(data);
                //     if(data.success)
                //     {
                //         //alert("用户已禁用");
                //         console.log('sucess~');
                //         that.asSearch();
                //         that.updatakey=!this.updatakey;
                //     }
                //     else 
                //     {
                //         console.log('error!!!'+data.message);
                //     }
                //     //console.log(data.data.content);
                //     //刷新表格
                // })
             },
            //批量禁用用户
            changSelectUserState() {
                let pid_arr=new Array();
                const LIST = this.multipleSelection;
                var that = this;
            if (LIST.length >= 1) {
              layer.confirm(
                "确定要禁用所选用户吗？",
                { icon: 3, title: "警告" },
                function (index) {
                  for (let i=0;i<LIST.length;i++)
                {
                  pid_arr[i]=LIST[i].id;
                }
                let pid_arr_data = pid_arr.join(',');
                let params  = 
                   {
                      pid:pid_arr_data
                   }
                $.post('/syatem/forbidden_User', params, function (data) {
                    //console.log(data);
                    if(data.success)
                    {
                        //alert("用户已禁用");
                        console.log('sucess~');
                        that.asSearch();
                        that.updatakey=!this.updatakey;
                    }
                    else 
                    {
                        console.log('error!!!'+data.message);
                    }
                    //console.log(data.data.content);
                    //刷新表格
                })
                  //关闭提醒框
                  layer.close(index);
                }
              );
            } else {
              layer.alert("未选择任何用户！");
            }
          },

          //页码相关
          handleCurrentChange(val) {
            this.currentPage = val;
          },
          //导入弹窗
          setResponse() {
            if (this.multipleSelection.length == 1) {
              asid = this.multipleSelection[0].asid;
              //打开弹窗
              layer.open({
                type: 2,
                title: "导入",
                shadeClose: true,
                shade: false,
                maxmin: true, //开启最大化最小化按钮
                area: ["860px", "600px"],
                content: "../component/main.html",
              });
            } else {
              layer.alert("请勾选单个预案后再点击设置！");
            }
          },
          //手动查询
          asSearchHandle() {
            if(this.unit == "")
            {
              this.$message.error("请选择单位!");
            }
            else {
              this.asSearch();
              //console.log(this.tableData);
            }
          },
          //查询部门并更新页面
          asSearch() {
            let that = this;
            let params = {
              companyid:this.unit?this.unit:1,
              name: this.searchForm.keyword,
              page:this.currentPage,
              size:this.pageSize,
            };
            axios
              .get("/syatem/query_dept", { params })
              .then((res) => {
                let data1 = res.data;
                //console.log(res.data);
                that.tableData = data1.data.content;
                that.totaldata = data1.data.totalElements;
                that.updatakey=!this.updatakey;
                this.dateTreetoCompany(data1.data.content);
                //console.log(data1.data.content);
                //console.log('一共有:'+data1.data.totalElements+'条数据');
              })
              .catch((err) => {
                console.log(err);
              });
            //let datearr=[];
            //console.log('选中了:'+arr1);
            //console.log('用户类型:'+that.unit);
          },
          toggleSelection(rows) {
            if (rows) {
              rows.forEach((row) => {
                this.$refs.multipleTable.toggleRowSelection(row);
              });
            } else {
              this.$refs.multipleTable.clearSelection();
            }
          },
          handleSelectionChange(val) {
            this.multipleSelection = val;
          },
          //获取所有单位
          getCompany() {
            axios
              .get("/syatem/query_company")
              .then((res) => {
                let data1 = res.data;
                console.log(data1);
                this.categoryList = data1.data.content;
                categoryList = data1.data.content;
                this.unit = this.categoryList[0].id;
                //console.log(this.unit);
              })
              .catch((err) => {
                console.log(err);
              });
          },
          //获取父级数据
          getDatebyPid(pid)
          {
            for(let i=0;i<this.tableData.length;i++)
            {
               if(pid==this.tableData[i].id)
               {
                  return this.tableData[i];
               }
            }
          },

          //将部门信息变为树形结构数据(没调通)
          dateTreetoCompany1(data)
          {
                  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
                  // var datemap = new Object();
                  // data.forEach(function (item) {
                  //   datemap[item.id] = item;
                  // });
                  // console.log(datemap);
               let that = this;
                  data.forEach(function (item) {
                      // 以当前遍历项，的parent,去datemap对象中找到索引的id
                      //let  parent = datemap[item.parent];
                      // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
                      //console.log('item...'+item);
                      if (item.parent) {
                        that.getDatebyPid(item.parent).children.push(item);
                          //console.log(item.id+'haveparent id'+parent);
                          //(parent.children || ( parent.children = [] )).push(item);

                      } else {
                          //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
                          datetree.push(item);
                      }
                  });
                  console.log(datetree);
          }
        },
      });
    </script>
  </body>
</html>
